//
//  LoginViewModel.swift
//  Link
//
//  Created by melvyn on 2018/8/20.
//  Copyright © 2018 NEET. All rights reserved.
//

import Foundation
import Alamofire
#if canImport(RxCocoa)
import RxSwift
import RxCocoa
#endif

class LoginViewModel {
    
    #if canImport(RxCocoa)
    var attemptToLogin: PublishSubject<Void> = PublishSubject()
    var isLoginEnabled: Driver<Bool> = Driver.never()
    var didLoggedIn: Driver<Result<AuthSession>> = Driver.never()
    
    init(_ input: (username: Observable<String>, password: Observable<String>)) {
        
        let validatedUsername = input.username.flatMapLatest {
            BehaviorRelay(value: $0.count > 0).asObservable()
        }
        let validatePassword = input.password.flatMapLatest {
            BehaviorRelay(value: $0.count > 0).asObservable()
        }
        
        didLoggedIn = attemptToLogin
            .withLatestFrom(Observable.combineLatest(input.username, input.password))
            .flatMapLatest {
                APIClient.default.rx.attemptAppLogin($0)
        }
        .asDriver(onErrorJustReturn: Result.failure(APIError.undefine))
        
        let signingIn = BehaviorRelay(value: false)
        
        isLoginEnabled = Observable.combineLatest(validatedUsername, validatePassword, signingIn)
            .map { $0 && $1 && !$2 }
        .asDriver(onErrorJustReturn: true)
    }
    
    #else
    var input: BasicAuthorization = ("", "")
    var didLoggedIn: ((Result<AuthSession>) -> Void)?
    
    init() {}
    
    func signinEventHandler() {
        APIClient.default.attemptAppLogin(input, completionHandler: { [weak self] in
            self?.didLoggedIn?($0)
        })
    }
    #endif
}

